<template>
  <div class="second-page">
    <div class="top-count ">
      <div class="top-count-left-box">
        <p class="text">今日终端累计启动量</p>
        <div class="num-box">
          <!-- <div class="add-tips" v-if="todayNumberStart > 0">{{todayNumberStart}}</div> -->
          <!-- <template v-if="!todayData">
            <div v-for="(item, index) in '----'" 
              :key='index' 
              class="num-box-item">
              <span>{{item}}</span>
          </div>
          </template> -->
          <ComNumberScroll
            :start="todayNumberStart" 
            :end="todayData"
            :autoPlay="true" 
            :duration="1000"
            :default="0"
            showType="tms-bg"
            :tipData="lastNum"
           />
        </div>
      </div>
      <div class="top-count-center-box">
            <div class="title">近7天开机率</div>
            <div class="layout-right">
              <div class="layout-right-num">
              <ComNumberScroll
                :start="0" 
                :end="sevenTotal"
                :autoPlay="true" 
                :duration="1000"
                :default="0"
                showType="no-bg"/>          
              </div>
              <ComBaseEcharts
                echartId="TmsFirstPagesevenAppStart"
                :options="getOptionsForRightpieSevenRef"
                :customStyle="{width: '50%', height: '100%'}"
              />
            </div>
      </div>
      <div class="top-count-right-box">
            <div class="title">TMS激活终端类型占比</div>
              <ComBaseEcharts 
                 echartId="TmsFirstPageapplySumId"
                :options="getOptionsForAppAllPieRef"
                :customStyle="{width: '100%', height: '90%'}"/>
      </div>   
    </div>
    <div class="center-box">
      <div class="center-box-left">
        <ComNavTab text="激活终端地区分布"/>
        <ComMap echartId="TmsfirstPlacePage1" style="width:750px;height:86%;" :data="centerMapData"  :showTipText="{'text1':'激活总量', 'text2':'近期激活'}"/>/>
      </div>
      <div class="center-box-right">
        <ComNavTab text="激活终端地区排名"/>
        <ComBaseEcharts echartId="TmsFirstgetOptionsForRankBarRe"
                         :options="getOptionsForRankBarRef"
                         :customStyle="{width: '100%', height: '90%'}"/>
      </div>
      </div>
    <div class="bottom-box">
        <ComNavTab text="近7天活跃终端"/>
        <div class="tab-wrapper">
          <div class="tab-container">
            <div class="tabs">
              <div
                class="tabs-item"
                v-for="tab in tabs"
                :key="tab.value"
                :class="['tab-button', { active: currentTab === tab.value }]"
                @click="currentTabClick(tab.value)">
                {{ tab.label }}
              </div>
            </div>
          </div>
        </div>          
        <ComBaseEcharts
           echartId="TmsFirstLineBottomRe"
          :options="getOptionsForLineBottomRef"
          style="width:100%;height:78%;"
        />
    </div>
  </div>
</template>
<script setup>
  import { ref, onMounted, onUnmounted } from "vue";
  import { getToday} from '@/utils/func/util'
  import ComNavTab from '@/components/public/ComNavTab.vue';
  import ComMap from '@/components/public/ComMap.vue';
  import ComBaseEcharts from '@/components/public/ComBaseEcharts.vue'
  import { getOptionsForRankBar, getOptionsForLineBottom, getOptionsForRightpie, getOptionsForAppAllPie } from './option.js'
  import ComNumberScroll from '@/components/public/ComNumberScroll/ComNumberScroll.vue';
    /* eslint-disable */
// eslint-disable-next-line vue/no-setup-props-destructure
  import { getTodaySum, getSummary, getTmsType, getArea, getTmsDate } from '@/api/tms/tms.js'
  
  const interval5minCount = ref(null);
  const intervalAllId = ref(null);
  const intervalId = ref(null);
  const lastNum = ref(0)
  const todayNumberStart = ref(0)
  const todayData = ref(0)
  const prevData = ref(0)
  //7天应用启动
  const sevenNum = ref(0)
  const sevenTotal = ref(0)

  //tms激活终端类型占比
  const getOptionsForAppAllPieRef = ref(getOptionsForAppAllPie([]))
  const getOptionsForRightpieSevenRef = ref(getOptionsForRightpie(sevenNum.value, sevenTotal.value, '活跃占比'))
  const getOptionsForRankBarRef = ref(getOptionsForRankBar([]))

  //地图
  const centerMapData = ref([])

  //底部折线图
  const currentTab = ref('1')
  const xData = []
  const getOptionsForLineBottomRef = ref(getOptionsForLineBottom(xData,[],'1'))
  const tabs = ref( [
          { value: '1', label: '近7天' },
          { value: '2', label: '近30天' },
          { value: '3', label: '近60天' },
        ])

  const loadGetTodaySum = () => {
    getTodaySum().then(res => {
      const { data } = res;
      prevData.value = Number(data);
      clearInterval(interval5minCount.value);
      if (window.sessionStorage.getItem('lastNum')) {
        lastNum.value = 0;

        console.log(`最新数据--prevData--${prevData.value}`);
        console.log(`存量数据--todayData--${todayData.value}`);

        const lastNumStr = window.sessionStorage.getItem('lastNum');
        const lastNumValue = lastNumStr ? Number(lastNumStr) : 0;

        let totalValue = Number(prevData.value) - lastNumValue;
        console.log(`初始数值/差值：${totalValue}`);

        if (totalValue <= 0) {
          todayData.value = prevData.value;
          return;
        }

        const totalSeconds = 299; // 5分钟 * 60秒/分钟
        const consumeValuePerSecond = Math.floor(totalValue / totalSeconds);
        console.log(`每秒消耗的数值（取整）${consumeValuePerSecond}`);
        const lastSecondExtraConsume = totalValue - (consumeValuePerSecond * (totalSeconds - 1));

        let currentValue = totalValue;

        function consumeValue() {
          // console.log(`当前数值：${currentValue}`);
          if (currentValue > 0) {
            if (currentValue <= lastSecondExtraConsume) {
              currentValue = 0;
              todayData.value = prevData.value;
              todayNumberStart.value = prevData.value;
              lastNum.value = totalValue;
            } else {
              currentValue -= consumeValuePerSecond;
              todayNumberStart.value = todayData.value;
              todayData.value += consumeValuePerSecond;
             
              lastNum.value += consumeValuePerSecond;
            }
          } else {
            clearInterval(interval5minCount.value); // 清除定时器
          }
        }

        interval5minCount.value = setInterval(consumeValue, 1000);
      } else {
        todayData.value = data;
      }
    })
};
  const loadData = () => {
    getSummary({statDate: getToday()}).then(res => {
      const { data } = res
      sevenTotal.value = data.totalActiveTerms
      sevenNum.value = data.activeTermsForPast7Days.toLocaleString()
      getOptionsForRightpieSevenRef.value = getOptionsForRightpie(data.activeTermsForPast7Days, data.totalActiveTerms, '开机率', data.percentageForPast7Days,)
    })
  }
  const loaddMapData = () => { 
    getArea({ statDate: getToday() }).then(res => {
      const { data } = res
      if(data.length > 0){
        centerMapData.value = data.map(item => ({
          name: item.areaName,
          value: item.totalActiveTerms,
          today: item.newActiveTerms
        }))
        //tms激活终端排行数据top10
        const rankData = data.slice(0, 10)
        const yLabel = rankData.map(v => v.areaName)
        const yData = rankData.map(v => v.totalActiveTerms)
        getOptionsForRankBarRef.value = getOptionsForRankBar([], yData, yLabel)
      }
    })
  }
  onMounted(() => {
    window.sessionStorage.removeItem('lastNum')
    loadGetTodaySum()
    loadData()
    loaddMapData()
    //tms激活终端
    getTmsType({statDate: getToday()}).then(res => {
      const { data } = res
      const activeSum = data.map(v=>({
          value: v.totalActiveTerms,
          name: v.termType
      }))
      getOptionsForAppAllPieRef.value = getOptionsForAppAllPie(activeSum)
    })
  })
    const getLineDataFn = () => {
      let queryParam = {
        dateNum: currentTab.value == 1 ? 7 : currentTab.value == 2 ? 30 : 60,
        statDate: getToday()
      }
      getTmsDate(queryParam).then(res => {
        const { data } = res
        if(data.length > 0){
          const dataArr = data
          dataArr.sort((a, b) => new Date(a.statDate) - new Date(b.statDate));
          const xData = dataArr.map(v => v.statDate)
          const yData = dataArr.map(v => v.activeTerms)
          getOptionsForLineBottomRef.value = getOptionsForLineBottom(xData, yData, currentTab.value)
        }
      })
  }     
    //折线图
    getLineDataFn()
   //tab选项卡
   const currentTabClick = (value) => {
    currentTab.value = value
    getLineDataFn()
  }
  //5分钟刷新数据-累计应用总量/地图/今日应用总量
  intervalId.value = setInterval(() => {
    window.sessionStorage.removeItem('lastNum')
    window.sessionStorage.setItem('lastNum', prevData.value)
    loadGetTodaySum()
    loaddMapData()
  }, 5 * 1000 * 60)
  intervalAllId.value = setInterval(() => {
    loadData()
    getLineDataFn()
  }, (60 * 5) * 1000 * 60)
  onUnmounted(() => {
    // 清除定时器
    if (intervalId.value) clearInterval(intervalId.value);
    if (intervalAllId.value) clearInterval(intervalAllId.value);
    if (interval5minCount.value) clearInterval(interval5minCount.value);
  }); 
</script>
<style lang="scss" scoped>
.second-page {
  padding: 0 40px 60px 40px;
  .top-count {
    width: 100%;
    height: 200px;
    padding-top: 90px;
    display: flex;
    align-items: center;
    border-radius: 3px;
    margin-bottom: 16px;
    justify-content: space-between;
    .top-count-left-box{
      width: 38%;
      height: 180px;
      // margin-right: 30px;
      background: url('/src/assets/tms-today-wrapper.png') no-repeat 0 0;
      background-size: 100% 100%;
      text-align: center;
      display: flex;
      flex-direction: column;
      justify-items: center;
      align-items: center;
      padding: 20px;
        .num-box{
          // position: relative;
          display: flex;
          padding-top: 10px;
          font-size: 48px;
          width: 99%;
          height: 141px;
          background: url('/src/assets/tms-today-left.png') no-repeat 0 0;
          background-size: 100% 100%;          
        }
        .text{
          opacity: 0.7;
          font-size: 24px;
          text-align: center;
        }
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
      p{
        font-size: 36px;
        color: #FFFFFF;
        font-weight: 500;
        &:first-child{
          font-size: 24px;
          color: #FFFFFF;
          opacity:  0.7;
        }
      }
    }
    .top-count-center-box{
      .title{
        text-align: center;
        font-size: 24px;
        color: #FFFFFF;
        opacity: 0.7;
        font-weight: 500;
      }
      padding: 20px 25px;
      width: 24%;
      height: 180px;
      background: url('/src/assets/tms-today-little-index.png') 0 0 no-repeat;
      background-size: 100% 100%;
      .layout-right{
        display: flex;
        align-items: center;
        height: 90%;
        width: 100%;
        &-num{
          font-size: 36px;
          color: #fff;
          font-weight: bold;
        }
      }
    }
    .top-count-right-box{
      .title{
        text-align: center;
        font-size: 24px;
        color: #FFFFFF;
        opacity: 0.7;
        font-weight: 500;
      }
      padding: 20px;
      background: url('/src/assets/tms-today-little-index.png') 0 0 no-repeat;
      background-size: 100% 100%;
      height: 180px;
      width: 24%;
      // margin-left:30px;
    }
  }
  .center-box{
    display: flex;
    height: 500px;
    padding-top: 28px;
    background-image: url('/src/assets/BG2.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    &-left{
      width: 50%;
    }
    &-right{
      width: 50%;
      margin-left:20px;
    }
  }
  .bottom-box{
    height: 500px;
  }
}
.actived-style{
  color: #FFD042 !important;
}

.tab-container {
    padding-top: 20px;
    padding-left: 40px;
  }
.tabs {
    display: flex;
    border-radius: 10px;
  }
  .tabs-item{
    width: 100px;
    height: 36px;
    line-height: 36px;
    font-size: 16px;
    background: url('/src/assets/button_normal.png') 0 0 no-repeat;
    background-size: 100% 100%;
    color: #fff;
    cursor: pointer;
    text-align: center;
    margin-right: 10px;
    font-weight: bold;
  }
  .tabs-item.active {
    background: url('/src/assets/button_avtived.png') 0 0 no-repeat;
    background-size: 100% 100%;
    color: #4C98FF;
  }
</style>
<style lang="scss">
  /* //pie */
.tms-pie-tool-tip{
  position: relative;
  padding: 10px;
  width: 65px;
  height: 45px;
  color:#fff;
  border: 1px solid #fff;
  background: rgb(12, 21, 45);
  // overflow: auto;
}
.tms-pie-tool-tip .title{
  font-size: 13px;
  color: #FFFFFF;
  letter-spacing: 0;
  text-align: center;
  font-weight: 500;
  position: relative;
  top: -10px;
  text-align: left;
}
.tms-pie-tool-tip p {
  text-align: left;
    font-size: 12px;
    &.first-child{
      position: relative;
      top: -25px;
      span{
        color: #FFD042;
      }
    }
    &.last-item{
      position: relative;
      top: -43px;
    }
  }
</style>
